//
//  ChatBarFaceViewTopViewPageView.m
//  keyboard
//
//  Created by 遇水 on 16/3/12.
//  Copyright © 2016年 遇水. All rights reserved.
//

#import "ChatBarFaceViewTopViewPageView.h"
#import "FaceModel.h"
#import "NSString+Emoji.h"
#import "UIView+Extension.h"
#import "Utiles.h"




@implementation ChatBarFaceViewTopViewPageView


-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    
    return self;
}


/**
 *  无法显示内容是几个意思啊
 *
 *  @param dataSource
 */
-(void)setDataSource:(NSArray *)dataSource
{
    _dataSource = dataSource;
    
    //创建子控件
    for (NSInteger i = 0; i < dataSource.count + 1; i++) {
        UIButton *button = [[UIButton alloc]init];
        //控件创建出来了 就是不能显示内容
        if (i != dataSource.count) {
            FaceModel *model = dataSource[i];
            if (model.png) {
                [button setImage:[UIImage imageNamed:model.png] forState:UIControlStateNormal];
            } else if (model.code) { // 是emoji表情
                // 设置emoji
                [button setTitle:model.code.emoji forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:32];
            }
        }
        
        //设置内容
        if(i == dataSource.count ){
            [button setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
        }
        
        button.tag = i;
        
        //添加事件
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

        [self addSubview:button];
    }
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat edgeW = 10;
    NSUInteger count = self.dataSource.count;
    CGFloat buttonW = (self.width - 2 * edgeW) / faceMaxColum;
    CGFloat buttonH = (self.height - edgeW) / faceMaxRows;
    for (int i = 0; i<count + 1; i++) {
        UIButton *button = self.subviews[i];
        button.adjustsImageWhenHighlighted = NO;
        button.x = edgeW + (i%faceMaxColum) * buttonW;
        button.y = edgeW + (i/faceMaxColum) * buttonH;
        
        button.width = buttonW;
        button.height = buttonH;

    }

}

-(void)buttonAction:(UIButton *)button
{
    //通过通知将点击的那个button对应的模型传递出去
    if(button.tag == self.dataSource.count){
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationDelete object:nil];
    }else{
        NSDictionary *userInfo = @{ Face : self.dataSource[button.tag]};
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationFace object:nil userInfo:userInfo];
    }
  }

@end
